'use client';

import React, { useEffect, useState } from 'react';
import { Card, Table, Tag, Button, Space, Input, DatePicker, Select, message, Modal, Form } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { SearchOutlined } from '@ant-design/icons';
import Layout from '@/components/Layout';
import styled from '@emotion/styled';
import { getOnboardingList, OnboardingInfo, OnboardingStatus, OnboardingQueryParams, updateOnboardingStatus, getOfferResults } from '@/lib/onboarding';
import dayjs from 'dayjs';

const StyledCard = styled(Card)`
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  .ant-card-head {
    border-bottom: 1px solid #f0f0f0;
    margin-bottom: 0;
  }
  .ant-card-body {
    padding: 24px;
  }
`;

const SearchCard = styled(Card)`
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  .ant-card-body {
    padding: 16px 24px;
  }
  margin-bottom: 16px;
  .search-container {
    display: flex;
    align-items: center;
    white-space: nowrap;
    gap: 16px;
    > *:last-child {
      margin-left: auto;
    }
  }
`;

interface OnboardRecord {
  id: number;
  name: string;
  department: string;
  position: string;
  onboardDate: string;
  status: string;
}

const { RangePicker } = DatePicker;

const OnboardManagementPage = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<OnboardingInfo[]>([]);
  const [total, setTotal] = useState(0);
  const [approvalModalVisible, setApprovalModalVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState<OnboardingInfo | null>(null);
  const [approving, setApproving] = useState(false);
  const [form] = Form.useForm();
  const [searchForm, setSearchForm] = useState({
    name: '',
    onboardingTime: '',
    status: undefined as OnboardingStatus | undefined,
  });
  const [queryParams, setQueryParams] = useState<OnboardingQueryParams>({
    page: 1,
    pageSize: 10
  });

  // Offer接受情况模态框状态
  const [offerModalVisible, setOfferModalVisible] = useState(false);
  const [offerData, setOfferData] = useState<any[]>([]);
  const [offerTotal, setOfferTotal] = useState(0);
  const [offerLoading, setOfferLoading] = useState(false);
  const [offerQueryParams, setOfferQueryParams] = useState({
    page: 1,
    pageSize: 10,
    startTime: '',
    endTime: '',
    result: undefined as number | undefined,
  });

  const loadData = async (params: OnboardingQueryParams = queryParams) => {
    setLoading(true);
    try {
      // 只合并有值的搜索参数
      const searchParams: Record<string, any> = {};
      
      // 只添加有值的参数
      if (searchForm.name) {
        searchParams.intervieweeName = searchForm.name;
      }
      if (searchForm.onboardingTime) {
        searchParams.onboardingTime = searchForm.onboardingTime;
      }
      if (searchForm.status !== undefined) {
        searchParams.status = searchForm.status;
      }

      // 合并分页参数
      const mergedParams = {
        ...params,
        ...searchParams
      };

      const response = await getOnboardingList(mergedParams);
      
      if (response.code === 1) {
        setData(response.data.row);
        setTotal(response.data.total);
      } else {
        message.error(response.msg || '获取数据失败');
      }
    } catch (error: any) {
      console.error('获取入职管理数据失败:', error);
      // 只在非取消请求的情况下显示错误信息
      if (error?.name !== 'CanceledError') {
        message.error(error?.message || '获取数据失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData().catch(error => {
      console.error('初始化加载数据失败:', error);
    });

    // 组件卸载时取消正在进行的请求
    return () => {
      // 如果有取消请求的逻辑，在这里添加
    };
  }, []);

  const handleApprove = async () => {
    if (!currentRecord) return;
    
    try {
      setApproving(true);
      const values = await form.validateFields();
      
      const response = await updateOnboardingStatus({
        ids: [currentRecord.id],
        status: values.status,
        tryoutStartTime: values.tryoutStartTime.format('YYYY-MM-DDTHH:mm:ss'),
        tryoutEndTime: values.tryoutEndTime.format('YYYY-MM-DDTHH:mm:ss'),
        tryoutDuration: '6个月'
      });

      if (response.code === 1) {
        message.success('入职审批成功');
        setApprovalModalVisible(false);
        loadData(queryParams); // 刷新列表
      } else {
        message.error(response.msg || '审批失败');
      }
    } catch (error) {
      console.error('入职审批失败:', error);
      message.error('审批失败，请稍后重试');
    } finally {
      setApproving(false);
    }
  };

  const columns: ColumnsType<OnboardingInfo> = [
    {
      title: '姓名',
      dataIndex: 'intervieweeName',
      key: 'intervieweeName',
    },
    {
      title: '部门',
      dataIndex: 'deptName',
      key: 'deptName',
    },
    {
      title: '职位',
      dataIndex: 'positionName',
      key: 'positionName',
    },
    {
      title: '入职时间',
      dataIndex: 'onboardingTime',
      key: 'onboardingTime',
    },
    {
      title: '入职地点',
      dataIndex: 'onboardingPlace',
      key: 'onboardingPlace',
      width: 120,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: OnboardingStatus) => {
        const statusMap = {
          [OnboardingStatus.Pending]: { text: '未办理', color: 'gold' },
          [OnboardingStatus.Completed]: { text: '已办理', color: 'green' },
          [OnboardingStatus.Absent]: { text: '未到', color: 'red' },
        };
        const { text, color } = statusMap[status];
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      key: 'updateBy',
      width: 100,
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 100,
      render: (_, record) => (
        <Button 
          type="primary"
          disabled={record.status !== OnboardingStatus.Pending}
          onClick={() => {
            setCurrentRecord(record);
            setApprovalModalVisible(true);
          }}
        >
          入职审批
        </Button>
      ),
    },
  ];

  const handleSearch = () => {
    const params = {
      ...queryParams,
      page: 1,
    };
    setQueryParams(params);
    loadData(params);
  };

  const handleReset = () => {
    setSearchForm({
      name: '',
      onboardingTime: '',
      status: undefined,
    });
    const params = {
      page: 1,
      pageSize: 10
    };
    setQueryParams(params);
    loadData(params);
  };

  const handleTableChange = (pagination: any) => {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
    };
    setQueryParams(params);
    loadData(params);
  };

  // 加载Offer接受情况数据
  const loadOfferData = async (params = offerQueryParams) => {
    setOfferLoading(true);
    try {
      const response = await getOfferResults(params);
      
      if (response.code === 1) {
        setOfferData(response.data.row);
        setOfferTotal(response.data.total);
      } else if (response.code === 0) {
        // 当code为0时，不显示错误消息，只在控制台打印
        console.warn('获取Offer数据返回code为0:', response.msg);
      } else {
        message.error(response.msg || '获取数据失败');
      }
    } catch (error: any) {
      console.error('获取Offer接受情况数据失败:', error);
      // 只在非取消请求的情况下显示错误信息
      if (error?.name !== 'CanceledError') {
        message.error(error?.message || '获取数据失败，请稍后重试');
      }
    } finally {
      setOfferLoading(false);
    }
  };

  // Offer接受情况表格列定义
  const offerColumns: ColumnsType<any> = [
    {
      title: '应聘者姓名',
      dataIndex: 'intervieweeName',
      key: 'intervieweeName',
    },
    {
      title: '申请人',
      dataIndex: 'applicantName',
      key: 'applicantName',
    },
    {
      title: '审批人',
      dataIndex: 'approverName',
      key: 'approverName',
      render: (text: string | null) => text || '-',
    },
    {
      title: '发送时间',
      dataIndex: 'sendTime',
      key: 'sendTime',
      render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '过期时间',
      dataIndex: 'expiryTime',
      key: 'expiryTime',
      render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '接受结果',
      dataIndex: 'result',
      key: 'result',
      render: (result: number) => {
        const resultMap: Record<number, { text: string; color: string }> = {
          0: { text: '未选择', color: 'default' },
          1: { text: '接受', color: 'success' },
          2: { text: '拒绝', color: 'error' },
        };
        const { text, color } = resultMap[result];
        return <Tag color={color}>{text}</Tag>;
      },
    },
  ];

  return (
    <Layout>
      <div className="space-y-4">
        <SearchCard bordered={false}>
          <div className="search-container">
            <Input
              placeholder="姓名搜索"
              prefix={<SearchOutlined />}
              style={{ width: 180 }}
              value={searchForm.name}
              onChange={(e) => setSearchForm(prev => ({ ...prev, name: e.target.value }))}
            />
            <DatePicker.RangePicker 
              style={{ width: 260 }}
              placeholder={['入职开始日期', '入职结束日期']}
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              onChange={(dates) => {
                setSearchForm(prev => ({
                  ...prev,
                  onboardingTime: dates?.[0]?.format('YYYY-MM-DDTHH:mm:ss') || ''
                }));
              }}
            />
            <Select
              placeholder="入职状态"
              style={{ width: 110 }}
              value={searchForm.status}
              onChange={(value) => setSearchForm(prev => ({ ...prev, status: value }))}
              options={[
                { value: OnboardingStatus.Pending, label: '未办理' },
                { value: OnboardingStatus.Completed, label: '已办理' },
                { value: OnboardingStatus.Absent, label: '未到' },
              ]}
              allowClear
            />
            <Space size={8}>
              <Button
                onClick={() => {
                  setOfferModalVisible(true);
                  loadOfferData();
                }}
              >
                查看Offer情况
              </Button>
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                搜索
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </div>
        </SearchCard>

        <StyledCard
          title="入职管理列表"
          bordered={false}
        >
          <Table 
            columns={columns} 
            dataSource={data}
            rowKey="id"
            loading={loading}
            pagination={{
              total: total,
              current: queryParams.page,
              pageSize: queryParams.pageSize,
              showTotal: (total) => `共 ${total} 条记录`,
              showSizeChanger: true,
              showQuickJumper: true,
            }}
            onChange={handleTableChange}
          />
        </StyledCard>

        <Modal
          title="入职审批"
          open={approvalModalVisible}
          onCancel={() => {
            setApprovalModalVisible(false);
            setCurrentRecord(null);
            form.resetFields();
          }}
          footer={[
            <Button 
              key="cancel" 
              onClick={() => {
                setApprovalModalVisible(false);
                setCurrentRecord(null);
                form.resetFields();
              }}
            >
              取消
            </Button>,
            <Button 
              key="submit" 
              type="primary" 
              loading={approving}
              onClick={handleApprove}
            >
              确认
            </Button>
          ]}
        >
          <Form
            form={form}
            layout="vertical"
            initialValues={{
              status: OnboardingStatus.Completed,
              tryoutStartTime: '',
              tryoutEndTime: ''
            }}
          >
            <Form.Item
              name="status"
              label="审批结果"
              rules={[{ required: true, message: '请选择审批结果' }]}
            >
              <Select
                options={[
                  { value: OnboardingStatus.Completed, label: '通过' },
                  { value: OnboardingStatus.Absent, label: '未到' },
                ]}
              />
            </Form.Item>
            <Form.Item
              name="tryoutStartTime"
              label="试用期开始时间"
              rules={[{ required: true, message: '请选择试用期开始时间' }]}
            >
              <DatePicker 
                style={{ width: '100%' }}
                format="YYYY-MM-DD"
                onChange={(date) => {
                  if (date) {
                    const endDate = date.clone().add(6, 'months');
                    form.setFieldValue('tryoutEndTime', endDate);
                  }
                }}
              />
            </Form.Item>
            <Form.Item
              name="tryoutEndTime"
              label="试用期结束时间"
              rules={[{ required: true, message: '请选择试用期结束时间' }]}
            >
              <DatePicker 
                style={{ width: '100%' }}
                format="YYYY-MM-DD"
              />
            </Form.Item>
          </Form>
        </Modal>

        {/* Offer接受情况模态框 */}
        <Modal
          title="Offer接受情况"
          open={offerModalVisible}
          onCancel={() => {
            setOfferModalVisible(false);
            setOfferQueryParams({
              page: 1,
              pageSize: 10,
              startTime: '',
              endTime: '',
              result: undefined,
            });
          }}
          width={1000}
          footer={null}
        >
          <Space direction="vertical" style={{ width: '100%' }}>
            <Space wrap>
              <RangePicker
                showTime
                style={{ width: 380 }}
                placeholder={['发送开始时间', '发送结束时间']}
                onChange={(dates) => {
                  if (dates) {
                    setOfferQueryParams(prev => ({
                      ...prev,
                      startTime: dates[0]?.format('YYYY-MM-DDTHH:mm:ss') || '',
                      endTime: dates[1]?.format('YYYY-MM-DDTHH:mm:ss') || '',
                    }));
                  }
                }}
              />
              <Select
                placeholder="接受结果"
                style={{ width: 120 }}
                allowClear
                options={[
                  { value: 0, label: '未选择' },
                  { value: 1, label: '接受' },
                  { value: 2, label: '拒绝' },
                ]}
                value={offerQueryParams.result}
                onChange={(value) => {
                  setOfferQueryParams(prev => ({ ...prev, result: value }));
                }}
              />
              <Button type="primary" onClick={() => loadOfferData()}>
                查询
              </Button>
              <Button onClick={() => {
                setOfferQueryParams({
                  ...offerQueryParams,
                  startTime: '',
                  endTime: '',
                  result: undefined,
                });
                loadOfferData({
                  ...offerQueryParams,
                  startTime: '',
                  endTime: '',
                  result: undefined,
                });
              }}>
                重置
              </Button>
            </Space>
            <Table
              columns={offerColumns}
              dataSource={offerData}
              rowKey="id"
              loading={offerLoading}
              pagination={{
                total: offerTotal,
                current: offerQueryParams.page,
                pageSize: offerQueryParams.pageSize,
                showTotal: (total) => `共 ${total} 条记录`,
                showSizeChanger: true,
                showQuickJumper: true,
                onChange: (page, pageSize) => {
                  const newParams = {
                    ...offerQueryParams,
                    page,
                    pageSize,
                  };
                  setOfferQueryParams(newParams);
                  loadOfferData(newParams);
                },
              }}
            />
          </Space>
        </Modal>
      </div>
    </Layout>
  );
};

export default OnboardManagementPage; 